package com.ifcar.app.activity;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;

public class AccountLogin extends BaseActivity{

	private String rst = "";
	private EditText view_userName;
	private EditText view_password;
	private Button view_loginSubmit;
	/** 登录loading提示框 */
	private ProgressDialog proDialog;
	private String username;
	private String password;
	private boolean loginsuccess;
	/** 如果登陆失败,这个可以给用户确切的消息显示,true是网络连接失败,false是用户名和密码错误 */
	private boolean isNetError;
	
	private String NetErrorInfo = "";
	private SharedPreferences set_prefs;
	private boolean isonlylogin = true;//仅仅是登录记录帐号和cookie
	private String sharetitle="";//分享的内容
	private String shareurl="";//分享的URL
	private String seturl = "";//图集URL
	private String shareimg = ""; // 文章的第一个图片
	private boolean tie = false;
	private boolean ispic = false;
	private boolean sharefloor = false;
	private boolean isreply = false;//是否发跟贴
	private String board = "";
	private String postid = "";
	private String pnum = "";
	
	private boolean isRegister = false;
	private int userlength = 0;
	private int passlength = 0;
	private Button go_reigster;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.accountlogin);
		findViewsById();
		setListener();
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Bundle bundle = this.getIntent().getExtras();
        if (null != bundle) {
            isonlylogin = bundle.getBoolean("isonlylogin", false);
        }

        if (null != bundle && !isonlylogin) {
            isRegister = bundle.getBoolean("isRegister", false);
            if (isRegister) { // 注册
                String uname = bundle.getString("username");
                view_userName.setText(uname);
                userlength = uname.length();
                isonlylogin = true;
            } else {
                isonlylogin = false;

                sharetitle = bundle.getString("sharetitle");
                shareurl = bundle.getString("shareurl");
                shareimg = bundle.getString("shareimg");
                tie = bundle.getBoolean("tie", false);
                seturl = bundle.getString("seturl");
                ispic = bundle.getBoolean("ispic", false);
                sharefloor = bundle.getBoolean("sharefloor", false);
                board = bundle.getString("board");
                postid = bundle.getString("postid");
                pnum = bundle.getString("pnum");
                isreply = bundle.getBoolean("isreply", false);
            }
        } else {
            isonlylogin = true;

        }
		view_userName.requestFocus();
		
	}
	
	/** 初始化注册View组件 */
	private void findViewsById() {
		
		view_userName = (EditText) findViewById(R.id.loginusername);
		view_password = (EditText) findViewById(R.id.loginpassword);
		view_loginSubmit = (Button) findViewById(R.id.do_login_button);
		go_reigster = (Button) findViewById(R.id.go_reigster);
	}
	private void setButtonStatus(){
	    if(userlength>0 && passlength>0){
            view_loginSubmit.setEnabled(true);
        }else{
            view_loginSubmit.setEnabled(false);
        }
	}
	/** 设置监听器 */
	private void setListener() {
		
		view_loginSubmit.setOnClickListener(submitListener);
		go_reigster.setOnClickListener(registerneteaseListner);
		setButtonStatus();
		//用户名和密码输入监听
		view_userName.addTextChangedListener(new TextWatcher() {
		    private CharSequence temp;
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                userlength = temp.length();
                setButtonStatus();
            }
		    
		});
		view_password.addTextChangedListener(new TextWatcher() {
		    private CharSequence temp;
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                passlength = temp.length();
                setButtonStatus();
            }
            
        });
	}
	
	/** 登录Button Listener */
	private OnClickListener submitListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			String un = view_userName.getText()==null?"":view_userName.getText().toString();
			un.trim();
			if(!un.contains("@")){//默认为163.com
				view_userName.setText(un + "@163.com");
			}
			if(Tools.CheckNetwork(AccountLogin.this)){
			    
				proDialog = ProgressDialog.show(AccountLogin.this, "","正在登录...", true, true);
				
				Thread loginThread = new Thread(new LoginHandler());
                loginThread.start();
			
				
				
			}else{
			    
				isNetError = true;
				Message message = Message.obtain();
                message.what  = 1;
                Bundle bundle = new Bundle();
				bundle.putBoolean("isNetError", isNetError);
				message.setData(bundle);
				loginHandler.sendMessage(message);
			}
				
			
		}
	};
	
	/** 注册Button Listener */
	private OnClickListener registerListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent i = new Intent(AccountLogin.this, AccountRegister.class);
			startActivity(i);
		}
	};
	
	
	private OnClickListener registerneteaseListner = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            Intent i = new Intent(AccountLogin.this, AccountWebViewRegister.class);
            startActivity(i);
            AccountLogin.this.finish();
        }
    };
    private OnClickListener forgetpasswordListner = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            Intent i = new Intent(AccountLogin.this, AccountForgetPassword.class);
            startActivity(i);
        }
    };
    
	
	//异常处理提示
	Handler httpHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (proDialog != null) {
				proDialog.dismiss();
			}
			String errorinfo = msg.getData().getString("errorinfo");
			
				Toast.makeText(AccountLogin.this, errorinfo,
						Toast.LENGTH_SHORT).show();

		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBackClick(null);
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	public void goBackClick(View view){
		if(isRegister){
			Intent i = new Intent(this, AccountSettingActivity.class);
			startActivity(i);
		}
		finish();
	}
	
	@Override
	protected void onDestroy() {
		if(null!=proDialog&&proDialog.isShowing())
			proDialog.dismiss();
		super.onDestroy();
	}
	
	/** 登录后台通知更新UI线程,主要用于登录失败,通知UI线程更新界面 */
	Handler loginHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		    super.handleMessage(msg);
		    
		    if (proDialog != null && proDialog.isShowing()) {
                proDialog.dismiss();
            }
		    switch(msg.what){
		        
		        case 1:
		            isNetError = msg.getData().getBoolean("isNetError");
		            if (isNetError) {
		                Toast.makeText(app, "登录失败:网络异常或超时!"+NetErrorInfo,Toast.LENGTH_SHORT).show();
		            }else {
		                Toast.makeText(app, "登录失败:请输入正确的用户名和密码!",Toast.LENGTH_SHORT).show();
		            }
		            break;
		        case 2:
		            break;
		    };
		    
			
		}
	};
	

	class LoginHandler implements Runnable {
        
        public void run() {
            
            username = view_userName.getText().toString().trim();
            password = view_password.getText().toString();
            
            try {
                HttpPost httpRequest = new HttpPost(StringUtil.SSLXURL);

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));
                params.add(new BasicNameValuePair("product", "t"));
                params.add(new BasicNameValuePair("type", "1"));
              
                httpRequest.setEntity(new UrlEncodedFormEntity(params,
                        HTTP.UTF_8));
             

                HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is
                // established.
                int timeoutConnection = 60000;
                HttpConnectionParams.setConnectionTimeout(httpParameters,
                        timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT)
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 60000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                
                SchemeRegistry schReg = new SchemeRegistry();
                schReg.register(new Scheme("http",
                                           PlainSocketFactory.getSocketFactory(),
                                           80));
                schReg.register(new Scheme("https", 
                                            SSLSocketFactory.getSocketFactory(),
                                            443));
                
                ClientConnectionManager conMgr = new ThreadSafeClientConnManager(httpParameters,schReg);
                DefaultHttpClient regclient = new DefaultHttpClient(conMgr,httpParameters);
                Tools.setHttpClientHostProxy(regclient, AccountLogin.this);

                try {
                    HttpResponse httpResponse = regclient.execute(httpRequest);

                    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                        Header[] hds = httpResponse.getAllHeaders();

                        int isok = 0;

                        for (int index = 0; index < hds.length; index++) {

                            if ("Set-Cookie".equals(hds[index].getName())) {

                                String value = hds[index].getValue();
                            
                                String[] vs = value.split(";");

                                for (int i = 0; i < vs.length; i++) {

                                    String[] vss = vs[i].split("=");

                                    if ("NTES_SESS".equals(vss[0])) {

                                        rst = rst + vs[i] + ";";
                                        isok++;
                                        break;
                                    }
                                }

                            }

                        }

                        loginsuccess = true;

                        if (isok !=1) {

                            loginsuccess = false;
                        }

                        isNetError = false;

                    } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_GATEWAY_TIMEOUT) {
                        isNetError = true;
                        NetErrorInfo = "code:" + HttpStatus.SC_GATEWAY_TIMEOUT;
                    } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                        isNetError = true;
                        NetErrorInfo = "code:" + HttpStatus.SC_NOT_FOUND;
                    } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_GATEWAY) {
                        isNetError = true;
                        NetErrorInfo = "code:" + HttpStatus.SC_BAD_GATEWAY;
                    } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                        isNetError = true;
                        NetErrorInfo = "code:"+ HttpStatus.SC_SERVICE_UNAVAILABLE;
                    } else {

                        isNetError = true;

                    }
                } catch (Exception e) {
                    isNetError = true;
                    e.printStackTrace();
                } finally {
                    regclient.getConnectionManager().shutdown();
                }               

            } catch (Exception e) {

                isNetError = true;
                NetErrorInfo = "";

            }
            
           
            if (loginsuccess) {
                
                loginHandler.sendEmptyMessage(2);
                
                if(!username.contains("@")){
                    username = username + "@163.com";
                }
                
                set_prefs.edit().putString("account", username).commit();
                set_prefs.edit().putString("password", "").commit();
                set_prefs.edit().putString("cookie", rst).commit();
                

                
                if(!isonlylogin){
                    
                     if(isreply){
                         
                            Message msg = Message.obtain();
                            msg.what= 0;
                            msg.obj = "登录成功！";
                            privatehandler.sendMessage(msg);
                            
                       }else{
                        
                            Message msg = Message.obtain();
                            msg.what= 1;
                            privatehandler.sendMessage(msg);
                      }
                    
                
                } else {
                    Message msg = Message.obtain();
                    msg.what= 2;
                    privatehandler.sendMessage(msg);
                }
                
                
            }else{
                
              
                Message message = Message.obtain();
                message.what  = 1;
                Bundle bundle = new Bundle();
                bundle.putBoolean("isNetError", isNetError);
                message.setData(bundle);
                loginHandler.sendMessage(message);
            }
            
        }
        
    }
	
	
	private Handler privatehandler = new Handler() {
		
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch(msg.what) {
			
			case 0:
				String strmsg = (String)msg.obj;
				Toast.makeText(app, strmsg,Toast.LENGTH_SHORT).show();
				AccountLogin.this.finish();
				break;
			case 1:
			    Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setClass(AccountLogin.this, ShareToMicroBlog.class);
                Bundle bundle = new Bundle();
                bundle.putString("sharetitle", sharetitle);
                bundle.putString("shareurl", shareurl);
                bundle.putBoolean("tie", tie);
                bundle.putString("seturl", seturl);
                bundle.putBoolean("ispic", ispic);
                bundle.putString("shareimg", shareimg);
                //分享跟帖某层
                bundle.putBoolean("sharefloor", sharefloor);
                bundle.putString("pnum", pnum);
                bundle.putString("board", board);
                bundle.putString("postid", postid);
                
                intent.putExtras(bundle);
                startActivity(intent);
                AccountLogin.this.finish();
                break;
			case 2:
			    Intent aintent = new Intent(AccountLogin.this, AccountSettingActivity.class);
                setResult(RESULT_OK,aintent); 
                AccountLogin.this.finish();
                break;
				
			
			}
		}
	};
	
	 @Override
	    public void onApplyTheme() {
	        super.onApplyTheme();
	        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
	        themeSettingsHelper.setViewBackgroud(this, R.id.loginRoot, R.drawable.loginbg);
	        themeSettingsHelper.setViewBackgroud(this, R.id.top_space, R.drawable.top_background);
	        themeSettingsHelper.setTextViewColor(this, R.id.top_txt, R.color.main_title_color);
	        themeSettingsHelper.setViewBackgroud(this, R.id.do_login_button, R.drawable.netease_big_button);
	        themeSettingsHelper.setTextViewColor(this, R.id.do_login_button, R.color.list_title_color);
	        themeSettingsHelper.setViewBackgroud(this, go_reigster, R.drawable.topcomment_column);
            themeSettingsHelper.setTextViewColor(this, go_reigster, R.color.top_image_title_color);
	      //返回夜间模式
	        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
	        
	    }
}
